import axios from "axios";

export default {
    name: "StudentInfo",
    data() {
        return {
            studentInfo: [],
            searchValue: '',
        };
    },
    created: function() {
        this.fetchStudents();
    },
    methods: {
        // 显示学员信息
        async fetchStudents() {
            try {
                const url = "http://localhost:8081/student/list";
                const response = await axios.get(url);

                this.studentInfo = response.data.data.map(student => {
                    return {
                        ...student,
                        editing: false,
                    };
                });
            } catch (error) {
                console.error("Fetching students error:", error);
            }
        },

        // 编辑学员信息
        async saveEditedStudent(student) {
            try {
                const url = `http://localhost:8081/student/update/${student.id}`;
                const response = await axios.put(url, student);

                // If update is successful, refresh student list and show success message, cancel edit mode
                if (response.data.code === 20000) {
                    this.fetchStudents();
                    this.$message.success("编辑学生成功！");
                    student.editing = false;
                } else {
                    // If update fails, show error message or perform other actions
                    this.$message.error(`编辑学生失败：${response.data.message}`);
                }
            } catch (error) {
                console.error("Saving edited student error:", error);
            }
        },

        // 查询学员信息
        async search() {
            try {
                const url = `http://localhost:8081/student/search/${this.searchValue}`;
                const response = await axios.get(url);

                if (response.data.code === 20000) {
                    this.studentInfo = [response.data.data];
                    this.searchValue = '';
                    this.$message.success("查询成功！");
                } else {
                    this.searchValue = '';
                    this.$message.error(`查询出错：${response.data.message}`);
                }
            } catch (error) {
                console.error("Searching error:", error);
                alert("搜索学生出错，请检查输入的ID和网络连接。");
            }
        },
    },
};